﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;

namespace homework05_1
{
    // 商品类
    [Serializable]
    public class Goods
    {
        public string Name { get; set; }
        public double Price { get; set; }

        public Goods() { } // 添加无参构造函数

        public Goods(string name, double price)
        {
            Name = name;
            Price = price;
        }

        public override string ToString() => $"商品: {Name}, 价格: {Price}";
    }

    // 客户类
    [Serializable]
    public class Customer
    {
        public string Name { get; set; }

        public Customer() { } // 添加无参构造函数

        public Customer(string name) => Name = name;

        public override string ToString() => $"客户: {Name}";
    }

    // 订单明细类
    [Serializable]
    public class OrderDetails
    {
        public Goods Goods { get; set; }
        public int Quantity { get; set; }

        public OrderDetails() { } // 添加无参构造函数

        public OrderDetails(Goods goods, int quantity)
        {
            Goods = goods;
            Quantity = quantity;
        }

        public double TotalPrice => Goods.Price * Quantity;

        public override bool Equals(object obj)
        {
            if (obj is OrderDetails other)
            {
                return Goods.Name == other.Goods.Name && Quantity == other.Quantity;
            }
            return false;
        }

        public override int GetHashCode() => Goods.Name.GetHashCode() ^ Quantity;

        public override string ToString() => $"商品: {Goods.Name}, 数量: {Quantity}, 小计: {TotalPrice}";
    }

    // 订单类
    [Serializable]
    public class Order
    {
        public string OrderId { get; set; }
        public Customer Customer { get; set; }
        public List<OrderDetails> Details { get; set; } = new List<OrderDetails>();
        public double TotalAmount => Details.Sum(d => d.TotalPrice);

        public Order() { } // 添加无参构造函数

        public Order(string orderId, Customer customer)
        {
            OrderId = orderId;
            Customer = customer;
        }

        public void AddDetail(OrderDetails detail)
        {
            if (!Details.Contains(detail))
                Details.Add(detail);
        }

        public override bool Equals(object obj)
        {
            if (obj is Order other)
            {
                return OrderId == other.OrderId;
            }
            return false;
        }

        public override int GetHashCode() => OrderId.GetHashCode();

        public override string ToString() =>
            $"订单号: {OrderId}\n客户: {Customer.Name}\n明细:\n{string.Join("\n", Details)}\n总金额: {TotalAmount}";
    }

    // 订单服务类
    public class OrderService
    {
        private List<Order> orders = new List<Order>();

        public void AddOrder(Order order)
        {
            if (orders.Contains(order))
                throw new Exception($"订单 {order.OrderId} 已存在");
            orders.Add(order);
        }

        public void RemoveOrder(string orderId)
        {
            var order = orders.FirstOrDefault(o => o.OrderId == orderId);
            if (order == null)
                throw new Exception($"订单 {orderId} 不存在");
            orders.Remove(order);
        }

        public void UpdateOrder(Order newOrder)
        {
            var order = orders.FirstOrDefault(o => o.OrderId == newOrder.OrderId);
            if (order == null)
                throw new Exception($"订单 {newOrder.OrderId} 不存在");
            orders.Remove(order);
            orders.Add(newOrder);
        }

        // LINQ查询方法
        public List<Order> QueryByOrderId(string orderId) =>
            orders.Where(o => o.OrderId.Contains(orderId))
                  .OrderByDescending(o => o.TotalAmount)
                  .ToList();

        public List<Order> QueryByGoodsName(string goodsName) =>
            orders.Where(o => o.Details.Any(d => d.Goods.Name.Contains(goodsName)))
                  .OrderByDescending(o => o.TotalAmount)
                  .ToList();

        public List<Order> QueryByCustomer(string customerName) =>
            orders.Where(o => o.Customer.Name.Contains(customerName))
                  .OrderByDescending(o => o.TotalAmount)
                  .ToList();

        public List<Order> QueryByAmount(double minAmount) =>
            orders.Where(o => o.TotalAmount >= minAmount)
                  .OrderByDescending(o => o.TotalAmount)
                  .ToList();

        // 排序方法
        public void Sort() => orders.Sort((o1, o2) => o1.OrderId.CompareTo(o2.OrderId));

        public void Sort(Func<Order, Order, int> comparison) => orders.Sort(new Comparison<Order>(comparison));


        // 将订单导出为XML文件
        public void Export(string filePath)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
                using (FileStream fs = new FileStream(filePath, FileMode.Create))
                {
                    serializer.Serialize(fs, orders);
                }
                Console.WriteLine($"订单数据已成功导出到 {filePath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"导出失败: {ex.Message}");
                throw;
            }
        }

        // 从XML文件导入订单
        public void Import(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException($"文件 {filePath} 不存在");
                }

                XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {
                    List<Order> importedOrders = (List<Order>)serializer.Deserialize(fs);
                    orders.Clear();
                    orders.AddRange(importedOrders);
                }
                Console.WriteLine($"订单数据已成功从 {filePath} 导入");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"导入失败: {ex.Message}");
                throw;
            }
        }
    }

    class Program4_3
    {
        static void Main(string[] args)
        {
            try
            {
                OrderService service = new OrderService();

                // 测试数据
                var goods1 = new Goods("手机", 2000);
                var goods2 = new Goods("电脑", 5000);
                var customer1 = new Customer("张三");
                var customer2 = new Customer("李四");

                var order1 = new Order("001", customer1);
                order1.AddDetail(new OrderDetails(goods1, 2));
                order1.AddDetail(new OrderDetails(goods2, 1));

                var order2 = new Order("002", customer2);
                order2.AddDetail(new OrderDetails(goods2, 2));

                // 添加订单
                service.AddOrder(order1);
                service.AddOrder(order2);

                // 导出到XML
                string exportPath = "orders.xml";
                service.Export(exportPath);

                // 创建新服务并导入
                OrderService newService = new OrderService();
                newService.Import(exportPath);

                // 验证导入结果
                Console.WriteLine("\n导入后的订单数据:");
                newService.QueryByOrderId("").ForEach(o => Console.WriteLine(o + "\n"));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }
    }
}

